package com.qianfeng.nio;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;
import java.util.Set;

/**
 * Created by Jackiechan on 2022/7/5 14:34
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
public class NIO11Client {

    public static void main(String[] args) throws Exception {
        //先搞一个selector
        Selector selector = Selector.open();
        // 搞一个通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置为非阻塞
        socketChannel.configureBlocking(false);
        //客户端关心的是连接成功
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        //客户端要连接服务端
        socketChannel.connect(new InetSocketAddress("10.9.48.191", 23456));
        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            selectionKeys.forEach(selectionKey -> {
                //拿到通道
                SocketChannel socketChannel1 = (SocketChannel) selectionKey.channel();
                try {
                    if (selectionKey.isConnectable()) {

                        if (socketChannel1.isConnectionPending()) {
                            //正在处理连接
                            socketChannel1.finishConnect();//完成连接
                            //给服务器发送一条欢迎消息
                            ByteBuffer byteBuffer = ByteBuffer.allocate(512);
                            String msg = "hello,moto";
                            //我们要发送的数据
                            byteBuffer.put(msg.getBytes("gbk"));
                            //翻转
                            byteBuffer.flip();
                            //发送给服务端
                            socketChannel1.write(byteBuffer);
                            //关注收消息,有数据可以读
                            socketChannel1.register(selector, SelectionKey.OP_READ);
                            sendMsg(socketChannel1);
                        }


                    } else if (selectionKey.isReadable()) {
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        //读取收到的数据
                        while (true) {
                            byteBuffer.clear();
                            int read = socketChannel1.read(byteBuffer);
                            if (read > 0) {
                                byteBuffer.flip();
                                String msg = String.valueOf(Charset.forName("gbk").decode(byteBuffer));
                                System.err.println(msg);
                            } else {
                                break;
                            }
                        }


                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });


            selectionKeys.clear();

        }

    }


    public static void sendMsg(SocketChannel socketChannel) {
        new Thread() {
            @Override
            public void run() {

                try {
                    System.err.println("请输入要发送 的内容");
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    Scanner scanner = new Scanner(System.in);
                    while (true) {
                        if (scanner.hasNext()) {
                            byteBuffer.clear();
                            String next = scanner.next();
                            byteBuffer.put(next.getBytes("gbk"));
                            byteBuffer.flip();
                            socketChannel.write(byteBuffer);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
